package unit

import (
	"fmt"
	"math"
	"strconv"
)

const (
	kilo = 1024
	two  = 2
	ten  = 10
	n64  = 64
)

// nolint
var (
	max = [6]int64{
		kilo,
		kilo * kilo,
		kilo * kilo * kilo,
		kilo * kilo * kilo * kilo,
		kilo * kilo * kilo * kilo * kilo,
		kilo * kilo * kilo * kilo * kilo * kilo,
	}
	unit = [6]int8{
		'B',
		'K',
		'M',
		'G',
		'T',
		'P',
	}
)

// Round 四舍五入.
func Round(f float64, num int) string {
	n10 := math.Pow10(num)

	return strconv.FormatFloat(math.Trunc((f+0.5/n10)*n10)/n10, 'f', -1, n64)
}

// ByteUnit 字节单位显示.
func ByteUnit(size int64) string {
	for index, m := range max {
		if size < m {
			f := float64(size)
			if index > 0 {
				f /= float64(max[index-1])
			}

			return fmt.Sprintf("%s%c", Round(f, two), unit[index])
		}
	}

	return strconv.FormatInt(size, ten)
}
